package in.falkeninc.umt_v0_9_8_1;

import java.util.Arrays;

public class AFW_String 
{

	/**
	 * Like PHP explode. Just a wrapper.
	 * @param stringToExplode
	 * @param separator
	 * @return The exploded string as an array of String[]
	 */
	public static String[] explode(String stringToExplode, String separator)
	{		
		return  stringToExplode.split(separator);
	}
	
	/**
	 * Like PHP implode. Java doesn't have this. This one saves from importing some Apache libs.
	 * @param arrayToImplode
	 * @param separator
	 * @return the imploded string
	 */
	public static String implode(String[] stringsToImplode, String separator)
	{		

		if (stringsToImplode.length == 0) {
			//empty array return empty string 
			return "";
		} else if(stringsToImplode.length == 1) {
			//only 1 item
			return stringsToImplode[0];
		}
		
		StringBuffer stringbuffer = new StringBuffer();
	    for (int i=0; i < stringsToImplode.length; i++) {
	        if (i != 0) stringbuffer.append(separator);
	        stringbuffer.append(stringsToImplode[i]);
	  	}

	  	return stringbuffer.toString();	
	}
	
	/**
	 * Returns a new string from 'str' with the character at 'index' replaced by 'replace'  
	 * @param str
	 * @param index
	 * @param replace
	 * @return
	 */
	public String replace(String str, int index, char replace)
	{     
	    if (str==null) {
	        return str;
	    } else if(index < 0 || index >= str.length()) {
	        return str;
	    }
	    char[] chars = str.toCharArray();
	    chars[index] = replace;
	    return String.valueOf(chars);       
	}
	
	/**
	 * 
	 * @param str
	 * @param letter
	 * @return Wether the supplied string contains the supplied character (given as a string) or not.
	 */
	public boolean contains(String str, String letter)
	{
		if (str.indexOf(letter)==-1)
		{
			return false;
		} else {
			return true;
		}
	}
	
	/** 
	 * Sorts the supplied string numerically
	 * @param str The sting to have sorted
	 * @return The modified string
	 */
	public String sort(String str)
	{
		char[] chars = str.toCharArray();
		Arrays.sort(chars);
		return new String(chars);
	}

}
